Importer.loadQtBinding("qt.core");
Importer.loadQtBinding("qt.network");
Importer.include("util.js");

PORT = 42620;

Server.prototype = new QTcpServer();

function Server(){
    Amarok.debug("Server()");
    QTcpServer.call(this, null);
    this.listen(new QHostAddress(QHostAddress.Any), PORT);
    if(!this.isListening()){
        Amarok.alert("Unable to open port "+PORT+" for the <i>Varan</i> server.");
    }
    Amarok.Window.Statusbar.longMessage("<b>Successfully started <i>Varan</i> server!</b> Port: "+this.serverPort());
    this.newConnection.connect(this, this.newConnectionCallback);
    //this.requestHandlerRegistry = new Object();
    //this.pendingRequestHandlerTimer = new QTimer();
    //this.pendingRequestHandlerTimer.timeout.connect(this, this.handlePendingRequests);
}

Server.prototype.newConnectionCallback = function(){
    Amarok.debug("newConnectionCallback");
    var socket = this.nextPendingConnection();
    socket.readyRead.connect(function() {
    	var request = new QByteArray();
	request.append(socket.readAll());
	var message = request.toString();
        //Amarok.alert("Received: " + request.toString());
	Amarok.debug("Received: " + message);
        if (message =="Play") {
	    Amarok.Engine.Play();
        }
        if (message == "Pause") {
	    Amarok.Engine.Pause();
        }
	if (message == "Stop") {
	    Amarok.Engine.Stop();
	}
	if (message == "Prev") {
	    Amarok.Engine.Prev();
	}
	if (message == "Next") {
	    Amarok.Engine.Next();
	}
    });	
}
